package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.MainActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.GoodsCartAdapter;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.MallGoods;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GoodsOrderDetailsActivity extends BaseActivity {


    @BindView(R.id.text_address)
    TextView textAddress;
    @BindView(R.id.re_view)
    RecyclerView reView;
    @BindView(R.id.note)
    EditText note;
    @BindView(R.id.numbers)
    TextView numbers;
    @BindView(R.id.t_total_price)
    TextView tTotalPrice;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.cancel_order)
    Button cancel_order;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.user_address)
    TextView userAddress;
    @BindView(R.id.relative_address)
    RelativeLayout relativeAddress;
    @BindView(R.id.pay_layout)
    LinearLayout payLayout;

    private GoodsCartAdapter adapter;
    private List<MallGoods> lists;

    private BigDecimal totalPrice;//总价
    private int totalNumber = 0;//总数

    private String orderNumber;
    private String state;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods_order_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        orderNumber = this.getIntent().getStringExtra("orderNumber");
        state = this.getIntent().getStringExtra("state");

        adapter = new GoodsCartAdapter(mActivity, handler, 0);
        lists = new ArrayList<>();
        reView.setLayoutManager(new LinearLayoutManager(mActivity));
        reView.setAdapter(adapter);

        if (state.equals("3")) {
            payLayout.setVisibility(View.VISIBLE);
        }

        getOrder();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        lists.clear();
                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");
                            JSONObject j_address = data.getJSONObject("address");

                            textAddress.setVisibility(View.GONE);
                            relativeAddress.setVisibility(View.VISIBLE);
                            userName.setText(j_address.getString("name"));
                            userPhone.setText(j_address.getString("phone"));
                            userAddress.setText(j_address.getString("province") + j_address.getString("county") + j_address.getString("city"));

                            JSONArray detailed = data.getJSONArray("detailed");
                            Gson gson = new Gson();
                            double price = 0;
                            for (int i = 0; i < detailed.length(); i++) {

                                MallGoods mg = gson.fromJson(detailed.getJSONObject(i).toString(), MallGoods.class);
                                lists.add(mg);
                                price = mg.getPrice() * mg.getNums() + price;
                                totalNumber = totalNumber + mg.getNums();

                            }
                            totalPrice = new BigDecimal(price);
                            totalPrice = totalPrice.setScale(2, RoundingMode.HALF_UP);
                            tTotalPrice.setText(Html.fromHtml("合计：<font color='#FF0000'>" + totalPrice + "</font>"));
                            if (totalNumber == 0) {

                                submit.setText("结算");
                            } else {

                                submit.setText("结算（" + totalNumber + "）");
                            }
                            adapter.setListAndNotifyDataSetChanged(lists);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray data = object.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {

                            if (data.getJSONObject(i).getInt("id") == 1) {

                                balance = new BigDecimal(data.getJSONObject(i).getString("moeny"));
                                pay_meney = data.getJSONObject(i).getInt("status");

                            }
                            if (data.getJSONObject(i).getInt("id") == 2) {

                                pay_wex = data.getJSONObject(i).getInt("status");

                            }
                            if (data.getJSONObject(i).getInt("id") == 3) {

                                pay_al = data.getJSONObject(i).getInt("status");

                            }

                        }

                        pop_up(balance);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1) {

                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }

        }
    };



    private Integer pay_meney = 0, pay_wex = 0, pay_al = 0;
    private BigDecimal balance;//钱包余额
    //弹出支付界面
    private Dialog modify_dialogs;//弹出框
    boolean balan = false;//判断余额是否够支付
    private Integer pay = 0;//支付方式1为余额。2为微信，3为支付宝

    public void pop_up(BigDecimal balance) {

        View view;//选择性别的view

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_pay_choose, null);

        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        TextView money = view.findViewById(R.id.money);
        money.setText("￥" + totalPrice.toString());

        ImageView wx_image, zfb_image, balance_image;
        wx_image = view.findViewById(R.id.wx_image);
        zfb_image = view.findViewById(R.id.zfb_image);
        balance_image = view.findViewById(R.id.balance_image);
        RelativeLayout wx_layout, zfb_layout, balance_layout;
        balance_layout = view.findViewById(R.id.balance_layout);
        if (pay_meney == 1) {
            balance_layout.setVisibility(View.GONE);
        }
        balance_layout.setOnClickListener(v -> {

            //判断余额是否足够
            if (balan) {

                pay = 1;
                balance_image.setVisibility(View.VISIBLE);
                wx_image.setVisibility(View.GONE);
                zfb_image.setVisibility(View.GONE);

            } else {

                Toast("余额不足本次支付!");

            }


        });

        zfb_layout = view.findViewById(R.id.zfb_layout);
        if (pay_al == 1) {
            zfb_layout.setVisibility(View.GONE);
        }
        zfb_layout.setOnClickListener(v -> {
            pay = 2;
            balance_image.setVisibility(View.GONE);
            wx_image.setVisibility(View.GONE);
            zfb_image.setVisibility(View.VISIBLE);
        });
        wx_layout = view.findViewById(R.id.wx_layout);
        if (pay_wex == 1) {
            wx_layout.setVisibility(View.GONE);
        }
        wx_layout.setOnClickListener(v -> {
            pay = 3;
            balance_image.setVisibility(View.GONE);
            wx_image.setVisibility(View.VISIBLE);
            zfb_image.setVisibility(View.GONE);
        });

        TextView balance_text = view.findViewById(R.id.balance_text);
        if (balance.compareTo(totalPrice) >= 0) {

            balance_text.setText(Html.fromHtml("账号余额 <font color='#FF0000'>" + balance + "</font>"));
            balan = true;

        } else {

            balan = false;
            balance_text.setText(Html.fromHtml("账号余额 <font color='#FF0000'>" + balance + "</font>（余额不足）"));

        }
        ImageView close = view.findViewById(R.id.close);
        close.setOnClickListener(v -> modify_dialogs.dismiss());


        Button button = view.findViewById(R.id.pay);
        button.setOnClickListener(v -> {

            if (pay == 0) {

                Toast("请选择支付方式!");

            } else {

                //先判断点击了哪种支付类型
                if (pay == 1) {

                    if (balan) {
                        payOrder(orderNumber);
                        modify_dialogs.dismiss();

                    }

                }
            }
        });

    }

    public void payOrder(String orderNumber) {

        List<String> ls = new ArrayList<>();
        ls.add(orderNumber);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "payOrder");
        params.put("data[order_id]", orderNumber);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 3, 404);

    }

    public void getPays() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getPays");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 2, 404);

    }

    public void getOrder() {

        List<String> ls = new ArrayList<>();
        ls.add(orderNumber);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getOrder");
        params.put("data[order_id]", orderNumber);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 1, 404);

    }

    public void closeOrder() {

        List<String> ls = new ArrayList<>();
        ls.add(orderNumber);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "closeOrder");
        params.put("data[order_id]", orderNumber);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/mall/", params, handler, 3, 404);

    }

    @OnClick({R.id.cancel_order, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancel_order:

                new AlertDialog.Builder(this).setTitle("确认取消吗？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                // 点击“确认”后的操作
                                closeOrder();

                            }
                        })
                        .setNegativeButton("再想想", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“返回”后的操作,这里不设置没有任何操作
                            }
                        }).show();


                break;
            case R.id.submit:
                getPays();
                break;
        }
    }
}
